package ar.edu.unrn.lia.bean.datamodel;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.faces.application.FacesMessage;
import javax.faces.context.FacesContext;
import javax.inject.Inject;

import org.primefaces.model.LazyDataModel;
import org.primefaces.model.SortMeta;
import org.primefaces.model.SortOrder;

import ar.edu.unrn.lia.model.Movimiento;
import ar.edu.unrn.lia.model.Propietario;
import ar.edu.unrn.lia.service.PropietarioService;



public class LazyPropietarioDataModel extends LazyDataModel<Propietario> {

	private static final long serialVersionUID = 1L;
	
	private static final String ORDER_DEFAULT = "id";

	private List<Propietario> list;

	@Inject
	PropietarioService entityService;
	
	

	public PropietarioService getEntityService() {
		return entityService;
	}

	public LazyPropietarioDataModel(PropietarioService entityService) {
		super();
		this.entityService = entityService;
	}

	@Override
	public List<Propietario> load(int startingAt, int maxPerPage,   
            List<SortMeta> multiSortMeta,Map<String, String> filters) {
		try {			
				
				Map<String, Boolean> sorts = new HashMap<String, Boolean>();
				if (multiSortMeta != null) {  
		            for (SortMeta sortMeta : multiSortMeta) {
		            	sorts.put(sortMeta.getSortField(), sortMeta.getSortOrder().name().equals(SortOrder.ASCENDING.toString()));	            	
		            }
				}
				
				list = getEntityService().getList(startingAt, maxPerPage,filters,sorts);
			
		} catch (Exception e) {
			e.printStackTrace();
			FacesMessage msg = new FacesMessage(FacesMessage.SEVERITY_ERROR,"Error Consulta",e.getMessage());
			FacesContext.getCurrentInstance().addMessage(null, msg);
			list = new ArrayList<Propietario>(0);
		}

		// set the total of list
		if (getRowCount() <= 0) {
			setRowCount(getEntityService().getCount(filters).intValue());
		}

		// set the page dize
		setPageSize(maxPerPage);

		return list;
	}

	@Override
	public Object getRowKey(Propietario entity) {
		return entity.getId();
	}

	@Override
	public Propietario getRowData(String entityId) {
		Integer id = Integer.valueOf(entityId);

		for (Propietario entity : list) {
			if (id.equals(entity.getId())) {
				return entity;
			}
		}

		return null;
	}

	public void setEntityService(PropietarioService entityService) {
		this.entityService = entityService;
	}

	public List<Propietario> getList() {
		return list;
	}

	public void setList(List<Propietario> list) {
		this.list = list;
	}
	
	
	
}